var User = require('../models/user')
module.exports = function (app) {
	app.use(function (req, res, next) {
		var _user = req.session.user
		app.locals.user = _user
		next()
	})
	 // 注册
	  app.post('/user/signup', function (req, res) {

	    var _user = req.body
	    console.log("用户注册请求:"+_user)
	    User.findOne({account: _user.account}, function (err, user) {
	      if (err) {
	        console.log(err)
	      }
	      if (user) {
	        res.json({
	          status: 1,
	          data: '',
            msg : '用户名已存在'
	        })
	      } else {
	        var user = new User(_user)
	        user.save(function (err, user) {
	          if (err) {
	            console.log(err)
	          }
	          res.json({
	            status: 0,
	            data: '注册成功',
              msg : ''
	          })
	        })
	      }
	    })
	  })
    // 登录
    app.post('/user/signin', function (req, res) {
      console.log("用户登录请求:"+req.body)
      var _user = req.body
      var account = _user.account
      var password = _user.password
      console.log(password)
      User.findOne({account: account}, function (err, user) {
        if (err) {
          console.log(err);
        }
        console.log(user)
        if (!user) {
          res.json({
            status: 1,
            data: '',
            msg : '用户不存在'
          })
        } else {
          if (!!password) {
            user.comparePassword(password, function (err, isMatch) {
              if (err) {
                console.log(err);
              }
              if (isMatch) {
                req.session.user = user;
                console.log('success');
                res.json({
                  status: 0,
                  data: '登录成功',
                  msg : ''
                })
              } else {
                res.json({
                  status: 1,
                  data: '',
                  msg : '密码不正确'
                })
                console.log('password is not meached');
              }
            })
          } else {
            res.json({
              status: -1,
              data: '',
              msg : '登录失败'
            })
          }
        }

      })
    })
}